#include "Player.h"
#include <iostream>

const int WIN_WIDTH = 2048;
const int WIN_HEIGHT = 1280;
const float GRAVITY = 1.28f; // 重力加速度

Player::Player(float p_x, float p_y, SDL_Texture *p_tex, int p_currentFrame, int p_animationFrames)
    : Entity(p_x, p_y, p_tex), currentFrame(p_currentFrame), animationFrames(p_animationFrames)
{
    setX(256);
    setY(WIN_HEIGHT - 500);
}

void Player::handleMouseButtonDown()
{
    if (!isJumpButtonPressed && isGround)
    {
        isJumpButtonPressed = true; // 鼠标已经按下
        jumpButtonPressTime = SDL_GetTicks();
    }
}

void Player::handleMouseButtonUp()
{
    if (isJumpButtonPressed && isGround)
    {
        isJumpButtonPressed = false;                                 // 鼠标松开
        jumpPower = sqrt(SDL_GetTicks() - jumpButtonPressTime) * 25; // 跳跃力量
        if (jumpPower < 100)
            jumpPower = 100;
        if (jumpPower > 1500)
            jumpPower = 1500;
        isJumping = true; // 设置人物正在起跳
    }
}

int Player::getScore()
{
    return score;
}

std::string Player::getScoreString()
{
    return "DISTANCE: " + std::to_string(score / 25);
}

void Player::update(Ground &ground)
{

    if (isGround || isJumping)
    {
        score++;
    }
    setX(getX() - 4);
    // 每帧跳跃距离
    if (isJumping && currentFrame <= 26)
    {
        float increment = jumpPower / 26;
        setX(getX() + increment);
        if (currentFrame <= 13)
        {
            setY(getY() - increment * 0.7);
        }
        else
        {
            setY(getY() + increment * 0.7);
        }
    }
    // 如果人物处于瓦片宽度之内
    if (ground.isTileBelow(getX(), getWidth()))
    {
        if (getY() + getHight() < WIN_HEIGHT - 256)
        {
            isGround = false;
        }
        else
        { // 缓冲40
            if (getY() < WIN_HEIGHT - getHight() - 256 + 40)
            {
                setY(WIN_HEIGHT - getHight() - 256);
                isGround = true;
            }
        }
    }
    else
    {
        isGround = false;
    }
    if (!isGround)
    {
        setY(getY() + GRAVITY);
    }
}

void Player::reset()
{
    setX(256);
    setY(WIN_HEIGHT - 500);
    score = 0;
}
